import compose from './compose.js';

export default function applyMiddleware(...middlewares) {
  return function(createStore) {
    return function (reducer, preloadedState) {
      const store = createStore(reducer, preloadedState);

      // 在dispatch没重写完前调用报错
      let dispatch = () => {
        throw new Error(
          'Dispatching while constructing your middleware is not allowed. ' +
            'Other middleware would not be applied to this dispatch.'
        );
      };

      const middlewareAPI = {
        getState: store.getState,
        dispatch: (action) => dispatch(action) 
      };

      // 调用中间件的第一层函数，保存middlewareAPI
      const chain = middlewares.map(middleware => middleware(middlewareAPI));

      // 重写dispatch
      dispatch = compose(...chain)(store.dispatch);

      // 返回增强后的store
      return {
        ...store,
        dispatch
      };
    }
  }
}